package com.chujian.framework.ws.support.srv;

import com.alibaba.fastjson.JSON;
import com.chujian.framework.exception.MsgException;
import com.chujian.framework.ws.WsMsg;
import com.chujian.framework.ws.IWsSendExecutor;
import com.chujian.framework.ws.exception.WsNotOnlineException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;


/**
 * 服务端推送到客户端的执行器
 */
@Slf4j
public class WsSrvSendExecutor implements IWsSendExecutor {

    @Override
    public void send(WsMsg msg) throws Exception {
        if (StringUtils.isEmpty(msg.getTarget())) {
            throw new MsgException("服务端推送时需要设置 msg.target");
        }
        WebSocketSession session = WsContext.getSession(msg.getTarget());
        if (null == session) {
            throw new WsNotOnlineException();
        }

        String msgStr = JSON.toJSONString(msg);
        log.debug("服务端推动消息：{}", msgStr);

        session.sendMessage(new TextMessage(msgStr));
    }

}
